import sys
import os
import base64
import configparser
from PyQt6.QtWidgets import (QApplication, QWidget, QMainWindow, QPushButton, QVBoxLayout,
                            QHBoxLayout, QLabel, QLineEdit, QMessageBox, QGraphicsDropShadowEffect,
                            QTabWidget, QCheckBox)
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QKeySequence, QShortcut, QPixmap, QPalette, QBrush, QColor, QIcon
from mainUi import MainWindow  # 提前导入MainWindow
from window_state import manager  # 改为导入manager

class LoginWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("瞬捷云链登录")
        
        # 初始化配置文件相关内容
        self.config_file = "user_config.ini"
        self.config = configparser.ConfigParser()
        self.create_config_if_not_exists()
        
        # 设置窗口为无边框模式，使顶部状态栏与背景融合
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        
        # 设置背景图片
        background = QPixmap("data/background.png")  # 确保图片文件在正确的路径
        palette = self.palette()
        palette.setBrush(QPalette.ColorRole.Window, QBrush(background.scaled(
            self.size(), 
            Qt.AspectRatioMode.IgnoreAspectRatio, 
            Qt.TransformationMode.SmoothTransformation
        )))
        self.setPalette(palette)
        
        # 当窗口大小改变时，确保背景图片也相应调整
        self.setAutoFillBackground(True)
        
        self.setStyleSheet("""
            QMainWindow {
                background-color: transparent;
            }
        """)
        
        # 设置窗口大小和位置
        screen = QApplication.primaryScreen().geometry()
        # 确保窗口大小不超过屏幕大小
        window_width = min(1100, screen.width() - 100)
        window_height = min(700, screen.height() - 100)
        self.resize(window_width, window_height)
        
        # 确保窗口位置在屏幕内
        self.move(
            max(0, (screen.width() - window_width) // 2),
            max(0, (screen.height() - window_height) // 2)
        )

        # 连接到状态管理器
        manager.state_changed.connect(self.on_state_changed)
        # 设置初始状态
        self.setWindowState(manager.state)

        # 预先创建主窗口实例
        self.main_window = MainWindow()

        # 创建中央部件并设置布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 30)
        
        # 添加关闭按钮
        close_button = QPushButton("×")
        close_button.setFixedSize(30, 30)
        close_button.setStyleSheet("""
            QPushButton {
                color: white;
                background-color: transparent;
                font-size: 20px;
                font-weight: bold;
                border: none;
                border-radius: 15px;
            }
            QPushButton:hover {
                background-color: rgba(255, 255, 255, 0.2);
            }
            QPushButton:pressed {
                background-color: rgba(255, 255, 255, 0.1);
            }
        """)
        close_button.clicked.connect(self.close)
        
        # 添加最小化按钮
        minimize_button = QPushButton("—")
        minimize_button.setFixedSize(30, 30)
        minimize_button.setStyleSheet("""
            QPushButton {
                color: white;
                background-color: transparent;
                font-size: 16px;
                font-weight: bold;
                border: none;
                border-radius: 15px;
            }
            QPushButton:hover {
                background-color: rgba(255, 255, 255, 0.2);
            }
            QPushButton:pressed {
                background-color: rgba(255, 255, 255, 0.1);
            }
        """)
        minimize_button.clicked.connect(self.showMinimized)
        
        # 创建顶部布局
        top_layout = QHBoxLayout()
        top_layout.setContentsMargins(0, 0, 0, 0)
        top_layout.addStretch()
        top_layout.addWidget(minimize_button)
        top_layout.addWidget(close_button)
        main_layout.addLayout(top_layout)
        
        # 创建标题和表单的整体布局
        content_layout = QHBoxLayout()
        content_layout.setContentsMargins(80, 60, 80, 60)
        main_layout.addLayout(content_layout)
        
        # 减少左侧占位，使登录框更靠左
        left_layout = QVBoxLayout()
        left_layout.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        left_layout.setSpacing(10)
        content_layout.addLayout(left_layout)
        
        # 缩小左侧空白
        content_layout.setStretch(0, 1)  # 左侧占比减小
        
        # 添加标志和标题
        logo_label = QLabel()
        logo_pixmap = QPixmap("logo.png")  # 如果有logo图片的话
        if not logo_pixmap.isNull():
            logo_label.setPixmap(logo_pixmap.scaled(200, 60, Qt.AspectRatioMode.KeepAspectRatio))
            left_layout.addWidget(logo_label)
        
        # 移除系统标题和副标题
        # 只保留左侧布局作为占位
        left_layout.addStretch()
        
        # 添加弹性空间
        content_layout.addStretch(1)
        
        # 创建右侧登录表单布局，向下偏移
        right_layout = QVBoxLayout()
        right_layout.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter) 
        right_layout.setContentsMargins(0, 100, 200, 0)  # 向下偏移
        content_layout.addLayout(right_layout)
        content_layout.setStretch(1, 3)  # 右侧占更多空间，使登录框更靠左
        
        # 登录表单容器
        form_container = QWidget()
        form_container.setFixedWidth(350)
        
        # 表单容器布局
        form_layout = QVBoxLayout(form_container)
        form_layout.setContentsMargins(0, 0, 0, 0)
        form_layout.setSpacing(0)
        
        # 创建选项卡标签
        tab_header = QHBoxLayout()
        tab_header.setAlignment(Qt.AlignmentFlag.AlignLeft)
        
        # 显式创建密码登录和验证码登录按钮作为选项卡头部 - 调整颜色和字体
        self.password_tab_button = QPushButton("密码登录")
        self.password_tab_button.setCheckable(True)
        self.password_tab_button.setChecked(True)
        self.password_tab_button.setFlat(True)
        self.password_tab_button.setStyleSheet("""
            QPushButton {
                background: transparent;
                color: #2E86C1;
                font-size: 16px;
                font-weight: bold;
                border: none;
                border-bottom: 2px solid #2E86C1;
                padding: 8px 20px;
                margin: 0;
            }
            QPushButton:!checked {
                color: #7FB3D5;
                border-bottom: 2px solid transparent;
                font-weight: normal;
            }
        """)
        
        self.verify_tab_button = QPushButton("验证码登录")
        self.verify_tab_button.setCheckable(True)
        self.verify_tab_button.setFlat(True)
        self.verify_tab_button.setStyleSheet("""
            QPushButton {
                background: transparent;
                color: #7FB3D5;
                font-size: 16px;
                border: none;
                border-bottom: 2px solid transparent;
                padding: 8px 20px;
                margin: 0;
            }
            QPushButton:checked {
                color: #2E86C1;
                border-bottom: 2px solid #2E86C1;
                font-weight: bold;
            }
        """)
        
        # 连接选项卡按钮点击事件
        self.password_tab_button.clicked.connect(self.show_password_tab)
        self.verify_tab_button.clicked.connect(self.show_verify_tab)
        
        tab_header.addWidget(self.password_tab_button)
        tab_header.addWidget(self.verify_tab_button)
        form_layout.addLayout(tab_header)
        
        # 创建堆叠的表单区域
        self.form_stack = QWidget()
        self.form_stack.setStyleSheet("background-color: transparent;")
        form_stack_layout = QVBoxLayout(self.form_stack)
        form_stack_layout.setContentsMargins(0, 25, 0, 0)
        form_stack_layout.setSpacing(20)
        
        # 创建密码登录表单
        self.password_form = QWidget()
        self.password_form.setStyleSheet("background-color: transparent;")
        password_layout = QVBoxLayout(self.password_form)
        password_layout.setContentsMargins(0, 0, 0, 0)
        password_layout.setSpacing(20)
        
        # 输入框样式 - 更接近图片效果
        inputStyle = """
            QLineEdit {
                background-color: white;
                border: 1px solid #E5E7E9;
                border-radius: 4px;
                padding: 10px 12px;
                font-size: 14px;
                color: #2C3E50;
            }
            QLineEdit:focus {
                border: 1px solid #3498DB;
            }
            QLineEdit::placeholder {
                color: #A6ACAF;
                font-size: 14px;
            }
        """
        
        # 用户名输入框
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("请输入手机号/账号")
        self.username_input.setFixedHeight(40)
        self.username_input.setStyleSheet(inputStyle)
        password_layout.addWidget(self.username_input)
        
        # 密码输入框
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("请输入密码")
        self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
        self.password_input.setFixedHeight(40)
        self.password_input.setStyleSheet(inputStyle)
        password_layout.addWidget(self.password_input)
        
        # 记住密码选项 - 调整颜色和字体
        remember_layout = QHBoxLayout()
        self.remember_checkbox = QCheckBox("记住密码")
        self.remember_checkbox.setStyleSheet("""
            QCheckBox {
                color: #7FB3D5;
                font-size: 14px;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
                border: 1px solid #7FB3D5;
                border-radius: 3px;
                background-color: transparent;
            }
            QCheckBox::indicator:checked {
                background-color: #2E86C1;
                border: 1px solid #2E86C1;
            }
        """)
        
        # 忘记密码链接样式 - 调整颜色和字体
        forgot_password = QLabel("忘记密码?")
        forgot_password.setStyleSheet("""
            color: #3498DB;
            font-size: 14px;
            background-color: transparent !important;
            border: none;
            padding: 0;
        """)
        forgot_password.setCursor(Qt.CursorShape.PointingHandCursor)
        
        remember_layout.addWidget(self.remember_checkbox)
        remember_layout.addStretch()
        remember_layout.addWidget(forgot_password)
        password_layout.addLayout(remember_layout)
        
        # 登录按钮 - 优化字体和样式
        self.login_button = QPushButton("登 录")
        self.login_button.setFixedHeight(40)
        self.login_button.setCursor(Qt.CursorShape.PointingHandCursor)
        self.login_button.setStyleSheet("""
            QPushButton {
                background-color: #3498DB;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2E86C1;
            }
            QPushButton:pressed {
                background-color: #2874A6;
            }
        """)
        password_layout.addWidget(self.login_button)
        
        # 创建验证码登录表单
        self.verify_form = QWidget()
        self.verify_form.setStyleSheet("background-color: transparent;")
        verify_layout = QVBoxLayout(self.verify_form)
        verify_layout.setContentsMargins(0, 0, 0, 0)
        verify_layout.setSpacing(20)
        
        # 手机号输入框
        self.phone_input = QLineEdit()
        self.phone_input.setPlaceholderText("请输入手机号")
        self.phone_input.setFixedHeight(40)
        self.phone_input.setStyleSheet(inputStyle)
        verify_layout.addWidget(self.phone_input)
        
        # 验证码输入区域
        verification_layout = QHBoxLayout()
        verification_layout.setSpacing(10)
        
        self.verification_input = QLineEdit()
        self.verification_input.setPlaceholderText("请输入验证码")
        self.verification_input.setFixedHeight(40)
        self.verification_input.setStyleSheet(inputStyle)
        
        self.get_code_button = QPushButton("获取验证码")
        self.get_code_button.setFixedHeight(40)
        self.get_code_button.setFixedWidth(120)
        self.get_code_button.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #3498DB;
                border: 1px solid #3498DB;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: rgba(52, 152, 219, 0.1);
            }
            QPushButton:pressed {
                background-color: rgba(52, 152, 219, 0.2);
            }
            QPushButton:disabled {
                color: #AED6F1;
                border: 1px solid #AED6F1;
            }
        """)
        
        verification_layout.addWidget(self.verification_input)
        verification_layout.addWidget(self.get_code_button)
        verify_layout.addLayout(verification_layout)
        
        # 验证码登录按钮 - 优化字体和样式
        self.verify_login_button = QPushButton("登 录")
        self.verify_login_button.setFixedHeight(40)
        self.verify_login_button.setCursor(Qt.CursorShape.PointingHandCursor)
        self.verify_login_button.setStyleSheet("""
            QPushButton {
                background-color: #3498DB;
                color: white;
                border: none;
                border-radius: 4px;
                font-size: 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #2E86C1;
            }
            QPushButton:pressed {
                background-color: #2874A6;
            }
        """)
        verify_layout.addWidget(self.verify_login_button)
        
        # 初始化表单堆栈 - 默认显示密码登录
        form_stack_layout.addWidget(self.password_form)
        self.verify_form.hide()
        form_stack_layout.addWidget(self.verify_form)
        
        # 添加底部注册选项
        register_layout = QHBoxLayout()
        register_layout.setContentsMargins(0, 10, 0, 0)
        
        register_text = QLabel("没有账号？")
        register_text.setStyleSheet("color: #7FB3D5; font-size: 14px;")
        
        register_link = QLabel("点击注册")
        register_link.setStyleSheet("""
            color: #3498DB;
            font-size: 14px;
            background-color: transparent !important;
            border: none;
            padding: 0;
            text-decoration: underline;
        """)
        register_link.setCursor(Qt.CursorShape.PointingHandCursor)
        
        register_layout.addStretch()
        register_layout.addWidget(register_text)
        register_layout.addWidget(register_link)
        register_layout.addStretch()
        
        form_stack_layout.addLayout(register_layout)
        form_layout.addWidget(self.form_stack)
        
        right_layout.addWidget(form_container)
        
        # 连接功能
        self.login_button.clicked.connect(self.login)
        self.verify_login_button.clicked.connect(self.login)
        forgot_password.mousePressEvent = self.forgot_password_clicked
        register_link.mousePressEvent = self.register_clicked
        self.get_code_button.clicked.connect(self.get_verification_code)
        
        # 加载保存的凭据
        self.load_credentials()

    def show_password_tab(self):
        if not self.password_tab_button.isChecked():
            self.password_tab_button.setChecked(True)
        self.verify_tab_button.setChecked(False)
        self.password_form.show()
        self.verify_form.hide()
    
    def show_verify_tab(self):
        if not self.verify_tab_button.isChecked():
            self.verify_tab_button.setChecked(True)
        self.password_tab_button.setChecked(False)
        self.verify_form.show()
        self.password_form.hide()

    def forgot_password_clicked(self, event):
        QMessageBox.information(self, "提示", "请联系管理员重置密码。")

    def register_clicked(self, event):
        QMessageBox.information(self, "提示", "注册功能暂未开放，请联系管理员。")
        
    def get_verification_code(self):
        phone = self.phone_input.text()
        if not phone:
            QMessageBox.warning(self, "提示", "请输入手机号")
            return
            
        # 模拟发送验证码
        QMessageBox.information(self, "提示", f"验证码已发送至 {phone}")
        
        # 禁用按钮并开始倒计时（实际应用中可以使用定时器）
        self.get_code_button.setEnabled(False)
        self.get_code_button.setText("60秒后重试")
        # 在实际应用中应添加定时器实现倒计时功能

    def login(self):
        # 根据当前选中的表单按钮判断登录方式
        if self.password_tab_button.isChecked():  # 密码登录
            username = self.username_input.text()
            password = self.password_input.text()
            
            # 简单验证，实际应用中应该连接到后端验证
            if username and password:  # 简化为任何非空输入都能登录
                # 如果勾选了"记住密码"，保存凭据
                if self.remember_checkbox.isChecked():
                    self.save_credentials(username, password)
                else:
                    # 如果没有勾选，清除保存的凭据
                    self.clear_credentials()
                
                self.hide()  # 隐藏登录窗口
                self.main_window.show()  # 直接显示预先创建的主界面
                self.close()  # 关闭登录窗口
            else:
                QMessageBox.warning(self, "错误", "请输入用户名和密码")
        else:  # 验证码登录
            phone = self.phone_input.text()
            code = self.verification_input.text()
            
            # 简单验证，实际应用中应该连接到后端验证
            if phone and code:  # 简化为任何非空输入都能登录
                self.hide()  # 隐藏登录窗口
                self.main_window.show()  # 直接显示预先创建的主界面
                self.close()  # 关闭登录窗口
            else:
                QMessageBox.warning(self, "错误", "请输入手机号和验证码")

    def on_state_changed(self, new_state):
        """响应全局窗口状态改变"""
        if self.windowState() != new_state:
            self.setWindowState(new_state)

    def changeEvent(self, event):
        if event.type() == event.Type.WindowStateChange:
            # 更新全局状态
            manager.state = self.windowState()
        super().changeEvent(event)
        
    def resizeEvent(self, event):
        """当窗口大小改变时，调整背景图片大小"""
        background = QPixmap("data/background.png")
        palette = self.palette()
        palette.setBrush(QPalette.ColorRole.Window, QBrush(background.scaled(
            self.size(),
            Qt.AspectRatioMode.IgnoreAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )))
        self.setPalette(palette)
        super().resizeEvent(event)

    # 添加鼠标事件处理，使无边框窗口可以拖动
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.MouseButton.LeftButton:
            self.move(event.globalPosition().toPoint() - self.drag_position)
            event.accept()

    # 创建配置文件（如果不存在）
    def create_config_if_not_exists(self):
        if not os.path.exists(self.config_file):
            self.config['Credentials'] = {
                'remember': 'False',
                'username': '',
                'password': ''
            }
            with open(self.config_file, 'w') as f:
                self.config.write(f)
        else:
            self.config.read(self.config_file)
    
    # 简单加密函数 - 实际应用中应使用更安全的加密方法
    def encrypt(self, data):
        if not data:
            return ""
        return base64.b64encode(data.encode()).decode()
    
    # 简单解密函数
    def decrypt(self, data):
        if not data:
            return ""
        try:
            return base64.b64decode(data.encode()).decode()
        except:
            return ""
    
    # 保存用户凭据
    def save_credentials(self, username, password):
        # 使用简单的base64编码存储密码 - 注意这不是安全的加密
        self.config['Credentials'] = {
            'remember': 'True',
            'username': username,
            'password': self.encrypt(password)
        }
        with open(self.config_file, 'w') as f:
            self.config.write(f)
    
    # 清除保存的凭据
    def clear_credentials(self):
        self.config['Credentials'] = {
            'remember': 'False',
            'username': '',
            'password': ''
        }
        with open(self.config_file, 'w') as f:
            self.config.write(f)
    
    # 加载保存的凭据
    def load_credentials(self):
        try:
            if self.config.has_section('Credentials'):
                remember = self.config.getboolean('Credentials', 'remember', fallback=False)
                if remember:
                    username = self.config.get('Credentials', 'username', fallback='')
                    encrypted_password = self.config.get('Credentials', 'password', fallback='')
                    password = self.decrypt(encrypted_password)
                    
                    # 设置用户名和密码
                    self.username_input.setText(username)
                    self.password_input.setText(password)
                    self.remember_checkbox.setChecked(True)
        except Exception as e:
            print(f"加载凭据时出错: {e}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = LoginWindow()
    window.show()
    sys.exit(app.exec())